﻿<?php 



set_time_limit(0);

$re=new isRead();

// echo '<pre>';

// 	var_dump($re->transpFiled());

// echo '</pre>';

var_dump($re->transpFiled());

while (true) {

	try {

		echo '<pre>';

			// var_dump($re->transpFiled());

			var_dump($re->transpFiled());
			// var_dump($re->getRenWuDb());

			// var_dump($re->getByrb(150888));

		echo '</pre>';		
		
	} catch (Exception $e) {
		
	}

}




class isRead
{

	public function getDataDb()
	{

		$json=file_get_contents('yidu.json');

		$arr=json_decode($json,true)['data'];
		$str='';

		foreach ($arr as $key => $value) {
			$str.=$value['callId']."','";
		}

		//echo strlen($str)-4;

		$str="('".substr($str,0,(strlen($str)-2)).")";

		return $str;
	}

	public function getRenWuDb(){   //获取要获取意向客户的任务ID

		$qure="SELECT * FROM byrgRenWuKongZhi WHERE isUp=1";
		$host='localhost';
		$user='root';
		$password='root';
		$database='weizandata';
		$link=mysqli_connect($host, $user, $password, $database);
		$link->query("set names utf8");
		$result=mysqli_query($link, $qure);
		$arr=mysqli_fetch_all($result, 1);


		return $arr;

	}
	public function getToke(){   //获取要获取百应的Cookie

		$qure="SELECT toke FROM toke WHERE name_i='bjrg'";
		$host='localhost';
		$user='root';
		$password='root';
		$database='weizandata';
		$link=mysqli_connect($host, $user, $password, $database);
		$link->query("set names utf8");
		$result=mysqli_query($link, $qure);
		$arr=mysqli_fetch_all($result, 1);


		return 'Cookie:'.$arr[0]['toke'];

	}
	public function posturl($url,$data){

        $data  = json_encode($data);
        $headerArray = array("Content-Type: application/json");
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $put = curl_exec($curl);

        curl_close($curl);

        return $put;
	}

	public function php_do_Url_GET($url,$params,$headers = null){ //Get get


		$url = "{$url}?" . http_build_query ($params);
		$ch = curl_init ();
		curl_setopt ( $ch, CURLOPT_URL, $url );
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'GET' );
		curl_setopt ( $ch, CURLOPT_TIMEOUT, 60 );
		curl_setopt ( $ch, CURLOPT_POSTFIELDS, $params );
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($ch, CURLOPT_SSLVERSION, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);	

		$json_string = curl_exec ( $ch );

		$data = json_decode($json_string, true);

		curl_close ( $ch );

		return $data;
	}


	public function insertDb($qure){


		//$qure="UPDATE by_data SET isRead=1 WHERE callInstanceId in {$id};";

		//echo $qure;

		$host='localhost';
		$user='root';
		$password='root';
		$database='weizandata';
		$link=mysqli_connect($host, $user, $password, $database);
		$link->query("set names utf8");
		$result=mysqli_query($link, $qure);
		//$arr=mysqli_fetch_all($result, 1);

		//echo mysqli_error($link);

		return ["result"=>$result,"row"=>mysqli_affected_rows($link),"erro"=>mysqli_error($link)];

	}

	public function getWhereDate(){

		$dateStar=date('Y-m-d 00：00：00');

		$dateEnd=date('Y-m-d 23：59：59');

		$wher=['FromDate'=>'2020/8/08 00:00:00','ToDate'=>'2020/8/10 23:59:59','KeyWord'=>'','ChannelID'=>'','ConsultantName'=>''];

		$data=['SqlWhere'=>json_encode($wher,JSON_UNESCAPED_UNICODE),'PageNum'=>'0',"PageSize"=>'20'];

		$a=self::posturl('http://go.qumei.com/api/CRM/CustomerDataDetail',$data);

		$count=json_decode($a,true)['Data']['TotalCount'];

		$pageNum=ceil($count/20);

		$row=0;

		for($i=0;$i<=$pageNum;$i++){

			$data=['SqlWhere'=>json_encode($wher,JSON_UNESCAPED_UNICODE),'PageNum'=>$i,"PageSize"=>'20'];
			$a=self::posturl('http://go.qumei.com/api/CRM/CustomerDataDetail',$data);

			$variable=json_decode($a,true)['Data']['Data'];

			$sqlstr=self::getFiled($variable);

			$qure="INSERT IGNORE INTO zhuanDanPhone ".$sqlstr['file']." values ".$sqlstr['val'];

			$result=self::insertDb($qure);

			if($result["result"]){

				$row+=$result["row"];
			}


		}


		return $row ;


	}


	public function getByrgc($customerId){ //获取百应人工外呼电话的意向



		$url = 'https://crm.byai.com/api/customer/listFollowRecordPage';

		$parmas =['customerId'=>$customerId,'pageSize'=>'30','pageNum'=>'1'];
		
		$headers[] = self:: getToke();

		$r = self::php_do_Url_GET($url,$parmas,$headers);


		return $r;
		

	}

	public function getByrga(){ //获取人工外呼任务列表



		$url = 'https://crm.byai.com/api/csTask/getTasks';

		$parmas = ['pageNum'=>'1','pageSize'=>'200','dataPermission'=>'WHOLE_COMPANY' ];


		$headers[] =  self:: getToke();

		// var_dump($headers);

		$r = self::php_do_Url_GET($url,$parmas,$headers);

		$list = $r['data']['list'];

		// var_dump($list);

		$listLen = count($list);

		for ($i=0; $i < $listLen; $i++) { 
			
			$csJobIds[]= [
				'csJobId'=>$list[$i]['csJobId'],   //任务ID
				'jobName'=>$list[$i]['jobName'],   //任务名称
				'doneCount'=>$list[$i]['doneCount'],  //完成个数
				'totalCount'=>$list[$i]['totalCount'],  //全部个数
				'calledCount'=>$list[$i]['calledCount'], //接通个数
				'validCalledCount'=>$list[$i]['validCalledCount'],//有效接通个数
				'totalTime'=>$list[$i]['totalTime'],//通话时长
				'validTotalTime'=>$list[$i]['validTotalTime'], //有效通话时长
				'startDate'=>$list[$i]['startDate'],//开始时间
				'status'=>$list[$i]['status'],//当前状态
				'lostCount'=>$list[$i]['lostCount'],//呼损数
				'userHangUpCount'=>$list[$i]['userHangUpCount'],//客户挂机数
			];

		}


		for ($i=0; $i < count($csJobIds) ; $i++) { 
			

			$keys = array_keys($csJobIds[$i]);

			$values = array_values($csJobIds[$i]);

			$keysStr = '('.implode(',',$keys).')';

			$valuesStr = '(\''.implode('\',\'',$values).'\')';

			$qure ='REPLACE INTO byrgRenWuList '.$keysStr.' value '.$valuesStr;

			self:: insertDb($qure);

			$qure1 ='INSERT IGNORE INTO  byrgRenWuKongZhi (csJobId,jobName) value (\''.$csJobIds[$i]['csJobId'].'\',\''.$csJobIds[$i]['jobName'].'\')';

			self:: insertDb($qure1);


		}



		return $csJobIds;


	}

	public function getByrb($taskId,$pageNum = 1,$pageSize = 1000){  //获取百应人工外呼电话列表



		$url = 'https://crm.byai.com/api/csTask/queryDoneTaskPhones';

		$parmas = ['pageNum'=>$pageNum,'pageSize'=>$pageSize,'taskId'=>$taskId,'finishStatus'=>0];


		$headers[] = self::getToke();

		$r = self::php_do_Url_GET($url,$parmas,$headers);


		return $r; 

	}

	public function caozuoby(){  //在任务中提取有效客资

		self ::getByrga();

		$list = self ::  getRenWuDb();

		$listLen = count($list) ;

		$phonelistArrSum =[];

		for ($i=0; $i < $listLen; $i++) { 
			
			$taskId  = $list[$i]['csJobId'];

			$phoneList = self:: getByrb($taskId);

			$pages = $phoneList['data']['pages'];

			$phonelistArr = $phoneList['data']['list'];


			if($pages > 1){

				for ($j=2; $j <= $pages; $j++) { 
					

					$phonelistArr = array_merge($phonelistArr ,self:: getByrb($taskId,$j)['data']['list']);

				}
			}

			$phonelistArrSum = array_merge($phonelistArrSum,$phonelistArr);


		}


		// $customerId='2454501171';

		$resi=[];//初始化输出变量

		// var_dump($phonelistArrSum[0]);

		for ($i=0; $i <count($phonelistArrSum) ; $i++) { 

			$customerId=$phonelistArrSum[$i]['customerId'];

			if($phonelistArrSum[$i]['customerId'] == $customerId){

				// var_dump($phonelistArrSum[$i]);

				$userLevel = self::getByrgc($customerId);

				$phoneeverSize=$userLevel['data']['size'];

				$phoneeverPageNum=$userLevel['data']['pageNum'];

				// var_dump($userLevel);

				for ($j=0; $j<$phoneeverSize; $j++) { 
						
					$phonLever=$userLevel['data']['list'][$j];

					$remark= $phonLever['remark'];

					// var_dump($phonLever);

					preg_match('/^A/',$remark,$return);

					if($return[0] == "A"){

						preg_match_all('/\S+/',$remark,$remarkArr);

						// var_dump($remarkArr);

						$CusAddress = preg_replace('/\d+|\|/', '', $phonelistArrSum[$i]['customerName']);
						

						$res = [

							'ConsultantName'=>$remarkArr[0][1],//客户姓名
							'CustomerName'=>'',  //称呼
							'CustomerPhone'=>$phonelistArrSum[$i]['customerTelephone'], //手机号
							'ChannelID'=>'1295239520261902336', //渠道ID
							'CusAddress'=>$CusAddress, //城市
							'CusXiaoQu'=>'',//小区名称
							'Remark'=>$remark,  //备注 具体家居需求
							'luYinUrl'=>$phonelistArrSum[$i]['luyinOssUrl'],  //录音
							'workName' =>$phonLever['followUserName'],
							'callJobName' =>$phonelistArrSum[$i]['jobName'],
							'uptime'=>$phonLever['gmtCreate'],
							
							];

						// var_dump($res);

						$resi[]=$res;

					}

					

				}

			}
		}



		return $resi;


	}

	public function transpFiled(){  //将有效客资存储到数据库

			

		$res = self::caozuoby();

		for ($i=0; $i < count($res) ; $i++) { 

			$keys = array_keys($res[$i]);

			$values = array_values($res[$i]);

			$keysStr = '('.implode(',',$keys).')';

			$valuesStr = '(\''.implode('\',\'',$values).'\')';

			$qure ='INSERT IGNORE INTO byrgGbqPhone '.$keysStr.' value '.$valuesStr;

			var_dump(self:: insertDb($qure));


		}

	}

}


?>